//
//  RHDeviceViewController.m
//  RuiHeAppApp
//
//  Created by Jun on 2023/7/25.
//

#import "RHDeviceViewController.h"
#import "JXCategoryView.h"
#import "JXCategoryListContainerView.h"
#import "RHDeviceListViewController.h"
#import "RHAddDeviceController.h"
#import "RHDeviceModel.h"
#import "RHDeviceListCell.h"
#import "RHDeviceInfoController.h"
#import "RHSearchView.h"

@interface RHDeviceViewController ()<JXCategoryListContainerViewDelegate,JXCategoryViewDelegate,JXCategoryTitleViewDataSource,QMUITextFieldDelegate>

@property (nonatomic, strong) NSMutableArray *titles;

@property (nonatomic, strong) NSMutableArray *controllers;

@property (nonatomic, strong) JXCategoryTitleView *categoryView;

@property (nonatomic, strong) JXCategoryListContainerView *listContainerView;

@property (nonatomic, strong) RHSearchView *searchView;
@end

@implementation RHDeviceViewController


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear: animated];
    [self.navigationController setNavigationBarHidden:NO];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"我的设备".rh_localized];
    [self.view setBackgroundColor:CFTabViewBgColor];
    self.titles = [NSMutableArray arrayWithArray:@[[NSString stringWithFormat:@"%@(0)",@"全部".rh_localized],
                                                   [NSString stringWithFormat:@"%@(0)",@"在线".rh_localized],
                                                   [NSString stringWithFormat:@"%@(0)",@"离线".rh_localized],
                                                   [NSString stringWithFormat:@"%@(0)",@"故障".rh_localized]
                                                   ]];
    self.controllers = [NSMutableArray arrayWithArray:@[@"",@"",@"",@""]];
    [self updateDevList];
    [self setupUI];
}

- (void)setupUI{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(updateDevList) name:DeviceListNeedUpdateNotification object:nil];
    kWeakSelf;
    //厂商,普通用户和终端用户才可以绑定设备
    if ([PrivateMange share].currentUser.hierarchyCode == UserRoleTypeNormalUser||[PrivateMange share].currentUser.hierarchyCode == UserRoleTypeTerminalUser) {
        UIButton *addButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0,40, 64)];
        [addButton setImage:[UIImage imageNamed:@"kwt_add_device"] forState:UIControlStateNormal];
        [addButton setBackgroundColor:UIColor.clearColor];
        [addButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
        [addButton.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [addButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
        UIBarButtonItem *rightBarBtn = [[UIBarButtonItem alloc] initWithCustomView:addButton];
        self.navigationItem.rightBarButtonItem = rightBarBtn;
        
        [[addButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            RHAddDeviceController *vc = [[RHAddDeviceController alloc] init];
            vc.AddSucceseBlock = ^{
                [weakSelf updateDevList];
            };
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }];
        
    }
    
    //搜索栏
    _searchView = [[RHSearchView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 55)];
    [self.view addSubview:_searchView];
    _searchView.delegate = self;
    _searchView.searchTextField.placeholder = @"请输入设备ID".rh_localized;
    
    
    _listContainerView = [[JXCategoryListContainerView alloc] initWithType:JXCategoryListContainerType_ScrollView delegate:self];
    [self.view addSubview:self.listContainerView];
    
    _categoryView = [[JXCategoryTitleView alloc] initWithFrame:CGRectMake(0,0, [UIScreen mainScreen].bounds.size.width, 50)];
    self.categoryView.titles = self.titles;
    self.categoryView.backgroundColor = [UIColor whiteColor];
    self.categoryView.delegate = self;
    self.categoryView.titleSelectedColor = CMainColorGreen;
    self.categoryView.titleColor = kCOLOR_HEX(@"969799");
    self.categoryView.titleFont = [UIFont systemFontOfSize:14];
    self.categoryView.titleSelectedFont = [UIFont boldSystemFontOfSize:14];
    self.categoryView.titleColorGradientEnabled = YES;
    self.categoryView.titleLabelZoomEnabled = NO;
    self.categoryView.titleLabelZoomScale = 1.0;
    self.categoryView.cellWidth = JXCategoryViewAutomaticDimension;//自动宽度
    self.categoryView.cellSpacing = 20;
//    self.categoryView.contentEdgeInsetLeft = 20;
//    self.categoryView.contentEdgeInsetRight = 20;
    self.categoryView.titleLabelVerticalOffset = -10;
    [self.view addSubview:self.categoryView];
    self.categoryView.listContainer = self.listContainerView;
    
    JXCategoryIndicatorBackgroundView *backgroundView = [[JXCategoryIndicatorBackgroundView alloc] init];
//     backgroundView.size = CGSizeMake(60, 3);//自动宽度
     backgroundView.indicatorColor = CMainColorGreen;
     backgroundView.indicatorHeight = 3;
//     backgroundView.indicatorWidth = 60;
     backgroundView.verticalMargin = -10;
     backgroundView.indicatorCornerRadius = 1.5;

     _categoryView.indicators = @[backgroundView];
    
    
    
    
    [_categoryView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(weakSelf.searchView.mas_bottom);
        make.height.mas_equalTo(50);
    }];
    
    [_listContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(self.categoryView.mas_bottom).offset(0);
        make.bottom.mas_offset(0);
    }];
    
    
}



//添加设备  设备分发成功后更新列表
-(void)updateDevList
{
    if(self.plantModel){
        [self getPlantDeviceCount];
    }else{
        [self getUserDeviceCount];
        //更新当前选择的
        UIViewController *currentVC = [self.listContainerView.validListDict objectForKey:@(self.categoryView.selectedIndex)];
        if ([currentVC isKindOfClass:[RHDeviceListViewController class]]) {
            RHDeviceListViewController *listVC = [self.listContainerView.validListDict objectForKey:@(self.categoryView.selectedIndex)];
            [listVC updateDeviceList];
        }
    }
}

//获取用户下的设备列表状态数量
-(void)getUserDeviceCount
{
    [BaseModel startGetWithCompletionAPIKey:H_userDeviceStatus argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            NSInteger allCount = [request.responseJSONObject[@"data"][@"all"] integerValue];
            NSInteger faultCount = [request.responseJSONObject[@"data"][@"fault"] integerValue];
            NSInteger offlineCount = [request.responseJSONObject[@"data"][@"offline"] integerValue];
            NSInteger onlineCount = [request.responseJSONObject[@"data"][@"online"] integerValue];
            NSArray *typeCountArr =  @[@(allCount),@(onlineCount),@(offlineCount),@(faultCount)];
            NSArray *titleArr = @[@"全部".rh_localized,@"在线".rh_localized,@"离线".rh_localized,@"故障".rh_localized];
            [self.titles removeAllObjects];
            for (int i = 0; i<titleArr.count; i++) {
                NSString *title = [NSString stringWithFormat:@"%@(%@)",titleArr[i],typeCountArr[i]];
                [self.titles addObject:title];
            }
            self.categoryView.titles = [self.titles copy];
            [self.categoryView reloadDataWithoutListContainer];
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        
    }];
}

//获取用电站下的设备列表状态数量
-(void)getPlantDeviceCount
{
    
    [BaseModel startGetWithCompletionAPIKey:H_plantDeviceStatus argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            NSInteger allCount = [request.responseJSONObject[@"data"][@"all"] integerValue];
            NSInteger faultCount = [request.responseJSONObject[@"data"][@"fault"] integerValue];
            NSInteger offlineCount = [request.responseJSONObject[@"data"][@"offline"] integerValue];
            NSInteger onlineCount = [request.responseJSONObject[@"data"][@"online"] integerValue];
            NSArray *typeCountArr =  @[@(allCount),@(onlineCount),@(offlineCount),@(faultCount)];
            NSArray *titleArr = @[@"全部".rh_localized,@"在线".rh_localized,@"离线".rh_localized,@"故障".rh_localized];
            [self.titles removeAllObjects];
            for (int i = 0; i<titleArr.count; i++) {
                NSString *title = [NSString stringWithFormat:@"%@(%@)",titleArr[i],typeCountArr[i]];
                [self.titles addObject:title];
            }
            self.categoryView.titles = [self.titles copy];
            [self.categoryView reloadDataWithoutListContainer];
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        
    }];
}

#pragma mark - JXCategoryViewDelegate

// 点击选中或者滚动选中都会调用该方法。适用于只关心选中事件，不关心具体是点击还是滚动选中的。
- (void)categoryView:(JXCategoryBaseView *)categoryView didSelectedItemAtIndex:(NSInteger)index {
    NSLog(@"%@", NSStringFromSelector(_cmd));
    // 侧滑手势处理
    self.navigationController.interactivePopGestureRecognizer.enabled = (index == 0);
    
}

// 滚动选中的情况才会调用该方法
- (void)categoryView:(JXCategoryBaseView *)categoryView didScrollSelectedItemAtIndex:(NSInteger)index {
    NSLog(@"%@", NSStringFromSelector(_cmd));
}

#pragma mark - JXCategoryListContainerViewDelegate
// 返回列表的数量
- (NSInteger)numberOfListsInlistContainerView:(JXCategoryListContainerView *)listContainerView {
    return  4;
}

// 返回各个列表菜单下的实例，该实例需要遵守并实现 <JXCategoryListContentViewDelegate> 协议
- (id<JXCategoryListContentViewDelegate>)listContainerView:(JXCategoryListContainerView *)listContainerView initListForIndex:(NSInteger)index {
    NSArray *typeArr = @[@(DevListTypeAll),@(DevListTypeOnline),@(DevListTypeOffline),@(DevListTypeFault)];
    RHDeviceListViewController *vc = [[RHDeviceListViewController alloc] init];
    vc.userId = self.userId;
    vc.plantModel = self.plantModel;
    vc.index = index;
    vc.listType = (DevListType)[typeArr[index] integerValue];
    kWeakSelf;
    //刷新
    vc.refreshBlock = ^() {
        weakSelf.searchView.searchTextField.text = nil;
        [weakSelf updateDevList];
    };
    if(![self.controllers containsObject:vc]){
        [self.controllers replaceObjectAtIndex:index withObject:vc];
    }
    return vc;
}




#pragma mark ------- textField delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    RHDeviceListViewController *listVC = (RHDeviceListViewController*)self.listContainerView.validListDict[@(self.categoryView.selectedIndex)];
    [listVC searchDeviceWithKeyCode:textField.text];
    [self.searchView resignFirstResponder];
    
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    RHDeviceListViewController *listVC = (RHDeviceListViewController*)self.listContainerView.validListDict[@(self.categoryView.selectedIndex)];
    [listVC searchDeviceWithKeyCode:@""];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.searchView resignFirstResponder];
    });
    return YES;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
